package cn.com.huzo.service.trade.impl;

import cn.com.huzo.model.entities.trade.DeliveryCommandSheetHeaderEntity;
import cn.com.huzo.model.entities.trade.ShippingOrderLinesDoEntity;
import cn.com.huzo.repository.trade.DeliveryCommandSheetHeaderRepository;
import cn.com.huzo.repository.trade.DeliveryCommandSheetLinesRepository;
import cn.com.huzo.repository.trade.ShippingOrderLinesDoRepository;
import huzofw.service.impl.GenericManagerImpl;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import cn.com.huzo.service.trade.ShippingOrderLinesDoManager;
import org.springframework.transaction.annotation.Transactional;
import cn.com.huzo.repository.trade.ShippingOrderLinesRepository;
import cn.com.huzo.service.trade.ShippingOrderLinesManager;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import huzofw.model.entities.paginator.Paginator;
import org.apache.commons.collections4.MapUtils;

/**
 * 发货单明细--引入发货款号管理服务对象类实现。
 *
 * @author 吴旭
 */
@Service("ShippingOrderLinesDoManager")
public class ShippingOrderLinesDoManagerImpl extends GenericManagerImpl<ShippingOrderLinesDoEntity, String>
        implements ShippingOrderLinesDoManager {

    @Resource(name = "ShippingOrderLinesRepository")
    private ShippingOrderLinesRepository _dao_lines;

    @Resource(name = "ShippingOrderLinesDoRepository")
    private ShippingOrderLinesDoRepository _dao_lines_do;

    @Resource(name = "ShippingOrderLinesManager")
    private ShippingOrderLinesManager _manager_lines;

    @Resource(name = "DeliveryCommandSheetHeaderRepository")
    private DeliveryCommandSheetHeaderRepository _dao_do_header;

    @Resource(name = "DeliveryCommandSheetLinesRepository")
    private DeliveryCommandSheetLinesRepository _dao_do_lines;

    /**
     * {@inheritDoc}
     *
     * @throws java.lang.Exception
     */
    @Transactional
    @Override
    public Map<String, Object> fetchByHeaderId(Long headerId) throws Exception {
        Map<String, Object> _result = new HashMap();

        _result.put("LinesDoList", _dao_lines_do.fetchByHeaderId(headerId));
        _result.put("LinesList", _dao_lines.fetchByHeaderId(headerId));

        return _result;
    }

    /**
     * {@inheritDoc}
     *
     * @throws java.lang.Exception
     */
    @Transactional
    @Override
    public List<Map<String, Object>> fetchSumQuantityByHeaderId(Long headerId) throws Exception {
        return _dao_lines_do.fetchSumQuantityByHeaderId(headerId);
    }

    /**
     * {@inheritDoc}
     *
     * @throws java.lang.Exception
     */
    @Transactional
    @Override
    public Map<String, Object> fetchForPage(Map<String, Object> criterion) throws Exception {
        Map<String, Object> _result = new HashMap();

        Long offset = (long) ((Integer) criterion.get("Limit")) * (((Integer) criterion.get("PageIndex")) - 1);
        long total = _dao_lines_do.fetchForCount(criterion);

        if (total > 0) {
            if (offset >= total) {
                offset = (total - MapUtils.getInteger(criterion, "Limit")) < 0 ? 0 : (total - MapUtils.getInteger(criterion, "Limit"));
            }
            criterion.put("Offset", offset);
            List<ShippingOrderLinesDoEntity> itemList = _dao_lines_do.fetchForPage(criterion);
            Paginator<ShippingOrderLinesDoEntity> paginator = new Paginator<>(itemList, offset, MapUtils.getInteger(criterion, "Limit"), total);

            _result.put("TotalRecordCount", paginator.getTotal());
            _result.put("TotalPages", paginator.getTotalPages());
            _result.put("PageIndex", paginator.getPageIndex());
            _result.put("DataList", paginator.getItemList());
            _result.put("Success", true);
        } else {
            _result.put("Success", false);
        }

        return _result;
    }

    /**
     * {@inheritDoc}
     *
     * @throws java.lang.Exception
     */
    @Transactional
    @Override
    public Map<String, Object> insert(Map<String, Object> criterion) throws Exception {
        Map<String, Object> _result = new HashMap();

        Map<String, Object> params = new HashMap();
        ObjectMapper mapper = new ObjectMapper();
        List<String> itemList;
        if (MapUtils.getInteger(criterion, "SelectAllFlag") == 1) {
            params.put("HeaderId", MapUtils.getLong(criterion, "DoHeaderId"));
            params.put("StyleNo", MapUtils.getString(criterion, "StyleNo"));
            itemList = _dao_do_lines.fetchAllSelectedLines(params);
        } else {
            itemList = mapper.convertValue(MapUtils.getObject(criterion, "ItemList"), new TypeReference<List<String>>() {
            });
        }

        if (itemList.isEmpty()) {
            _result.put("Success", false);
        } else {
            // step1: 增加引入的发货发令单明细
            params.clear();
            params.put("HeaderId", MapUtils.getLong(criterion, "HeaderId"));
            params.put("InCase", MapUtils.getInteger(criterion, "InCase"));
            params.put("CreatedBy", MapUtils.getLong(criterion, "UserId"));
            params.put("UpdatedBy", MapUtils.getLong(criterion, "UserId"));
            params.put("DoLinesIdList", itemList);
            Integer rowsAffected = _dao_lines_do.insert(params);
            if (rowsAffected > 0) {
                // step2: 清空发货单明细
                _dao_lines.deleteByHeaderId(MapUtils.getLong(criterion, "HeaderId"));
                // step3: 根据发货款号明细表重新生成发货单明细
                DeliveryCommandSheetHeaderEntity _entity = _dao_do_header.fetchByKey(MapUtils.getLong(criterion, "DoHeaderId"));
                _dao_lines.caclCartonNo(MapUtils.getLong(criterion, "HeaderId"), _entity.getIsAssortedColour(), _entity.getIsAssortedSize(),
                        _entity.getIsNewNoPerDestination(), _entity.getIsNewNoPerColour());

                // step4: 取得返回值
                _result.put("Success", true);

                params.clear();
                params.put("HeaderId", MapUtils.getLong(criterion, "HeaderId"));
                params.put("PageIndex", MapUtils.getInteger(criterion, "PageIndex01"));
                params.put("Limit", MapUtils.getInteger(criterion, "Limit01"));
                _result.put("LinesDoList", this.fetchForPage(params));

                params.clear();
                params.put("HeaderId", MapUtils.getLong(criterion, "HeaderId"));
                params.put("PageIndex", MapUtils.getInteger(criterion, "PageIndex02"));
                params.put("Limit", MapUtils.getInteger(criterion, "Limit02"));
                _result.put("LinesList", _manager_lines.fetchForPage(params));
                // 审计日志
                //writeAuditLog(itemList.get(0).getUpdatedBy(), "贸易信息→发货单明细款号", "单据号：" + itemList.get(0).getBillNo(), "增加");
            } else {
                _result.put("Success", false);
            }
        }

        return _result;
    }

    /**
     * {@inheritDoc}
     *
     * @throws java.lang.Exception
     */
    @Transactional
    @Override
    public Map<String, Object> update(Map<String, Object> criterion) throws Exception {
        Map<String, Object> _result = new HashMap();

        ObjectMapper mapper = new ObjectMapper();
        List<ShippingOrderLinesDoEntity> itemList = mapper.convertValue(MapUtils.getObject(criterion, "ItemList"), new TypeReference<List<ShippingOrderLinesDoEntity>>() {
        });

        if (itemList.isEmpty()) {
            _result.put("Success", false);
        } else {
            // step1: 更新
            Integer rowsAffected = _dao_lines_do.batchUpdate(itemList);
            if (rowsAffected > 0) {
                // step2: 清空发货单明细
                _dao_lines.deleteByHeaderId(MapUtils.getLong(criterion, "HeaderId"));
                // step3: 根据发货款号明细表重新生成发货单明细
                DeliveryCommandSheetHeaderEntity _entity = _dao_do_header.fetchByKey(MapUtils.getLong(criterion, "DoHeaderId"));
                _dao_lines.caclCartonNo(MapUtils.getLong(criterion, "HeaderId"), _entity.getIsAssortedColour(), _entity.getIsAssortedSize(),
                        _entity.getIsNewNoPerDestination(), _entity.getIsNewNoPerColour());

                // step4: 取得返回值
                _result.put("Success", true);

                Map<String, Object> params = new HashMap();
                params.put("HeaderId", MapUtils.getLong(criterion, "HeaderId"));
                params.put("PageIndex", MapUtils.getInteger(criterion, "PageIndex01"));
                params.put("Limit", MapUtils.getInteger(criterion, "Limit01"));
                _result.put("LinesDoList", this.fetchForPage(params));

                params.clear();
                params.put("HeaderId", MapUtils.getLong(criterion, "HeaderId"));
                params.put("PageIndex", MapUtils.getInteger(criterion, "PageIndex02"));
                params.put("Limit", MapUtils.getInteger(criterion, "Limit02"));
                _result.put("LinesList", _manager_lines.fetchForPage(params));

                // 审计日志
                //writeAuditLog(itemList.get(0).getUpdatedBy(), "贸易信息→发货单明细款号", "单据号：" + itemList.get(0).getBillNo(), "更新");
            } else {
                _result.put("Success", false);
            }
        }

        return _result;
    }

    /**
     * {@inheritDoc}
     *
     * @throws java.lang.Exception
     */
    @Transactional
    @Override
    public Map<String, Object> delete(Map<String, Object> criterion) throws Exception {
        Map<String, Object> _result = new HashMap();

        // step1: 删除引入的发货发令单
        Integer rowsAffected = _dao_lines_do.delete(MapUtils.getString(criterion, "LinesId"));

        if (rowsAffected > 0) {
            // step2: 清空发货单明细
            _dao_lines.deleteByHeaderId(MapUtils.getLong(criterion, "HeaderId"));
            // step3: 根据发货款号明细表重新生成发货单明细
            DeliveryCommandSheetHeaderEntity _entity = _dao_do_header.fetchByKey(MapUtils.getLong(criterion, "DoHeaderId"));
            _dao_lines.caclCartonNo(MapUtils.getLong(criterion, "HeaderId"), _entity.getIsAssortedColour(), _entity.getIsAssortedSize(),
                    _entity.getIsNewNoPerDestination(), _entity.getIsNewNoPerColour());

            // step4: 取得返回值
            _result.put("Success", true);
            Map<String, Object> params = new HashMap();
            params.put("HeaderId", MapUtils.getLong(criterion, "HeaderId"));
            params.put("PageIndex", MapUtils.getInteger(criterion, "PageIndex01"));
            params.put("Limit", MapUtils.getInteger(criterion, "Limit01"));
            _result.put("LinesDoList", this.fetchForPage(params));

            params.clear();
            params.put("HeaderId", MapUtils.getLong(criterion, "HeaderId"));
            params.put("PageIndex", MapUtils.getInteger(criterion, "PageIndex02"));
            params.put("Limit", MapUtils.getInteger(criterion, "Limit02"));
            _result.put("LinesList", _manager_lines.fetchForPage(params));
            // 审计日志
            //writeAuditLog(MapUtils.getLong(criterion, "DeletedBy"),
            //        "贸易信息→发货明细", "明细数据（" + MapUtils.getString(criterion, "LinesData") + "）",
            //        "删除明细");
        } else {
            _result.put("Success", false);
        }

        return _result;
    }
}
